package com.yudean.esb.rest.impl;

import com.yudean.esb.cached.ServicesCollection;
import com.yudean.esb.domain.esb.EsbServiceConfig;
import com.yudean.esb.rest.ServiceRouter;
import com.yudean.esb.service.ErpClientService;
import com.yudean.esb.service.handler.UniversalQueryService;
import com.yudean.esb.security.SecurtiyChecker;
import com.yudean.esb.util.ObjectPooledFactoy;
import com.yudean.esb.util.StringUtil;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 接管所有通用的查询请求
 *
 * @author : DL<duanlei@gdyd.com>
 * @version : 1.0
 */
@Controller("serviceRouterImpl")
@Scope("prototype")
public class ServiceRouterImpl implements ServiceRouter {
    private final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ServiceRouterImpl.class);
    @Resource
    private ErpClientService erpClientService;
    @Resource
    private SecurtiyChecker securtiyChecker;
    @Resource
    private UniversalQueryService universalQueryService;
    protected EsbServiceConfig serviceConfig;
    @Resource
    private Environment environment;


    private static String noData() {
        return errorMsg("-1", "返回数据为空！");
    }

    private static String noPermit() {
        return errorMsg("-1", "没有访问该服务的权限！");
    }

    private static String errorRequest() {
        return errorMsg("-1", "请求参数不可识别，请检查！");
    }

    /**
     * 返回错误信息
     *
     * @param result 错误结果
     * @param msg    错误信息详情
     * @return
     */
    private static String errorMsg(String result, String msg) {
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><service>")
                .append("<result>").append(result)
                .append("</result><msg>").append(msg)
                .append("</msg></service>");
        return sb.toString();
    }

    @Override
    public String get(String serviceID, String token, String page, String pageSize, String args) {
        LOGGER.info("get():request-{serviceID:{},token:{},page:{},pagesize:{},arg:{}}", serviceID, token, page, pageSize, args);
        try {
            erpClientService.addErpClientLog(token);
        } catch (Exception e) {
            LOGGER.error("save ERP log of /rest/get error:", e);
        }
        Map<String, Object> requestParams = new HashMap<String, Object>();
        //环境
        Profiles profiles = Profiles.of("prod");
        //获取项目的环境
        final boolean flag = environment.acceptsProfiles(profiles);
        String targetEnvironment = profiles.toString();
        if(flag){
            requestParams.put("targetEnvironment",targetEnvironment);
        }else{
            requestParams.put("targetEnvironment","dev");
        }
        //验证传入参数是否合法
        if(StringUtil.isEmpty(serviceID)||StringUtil.isEmpty(token)){
            return errorRequest();
        }
        int pageNo = 0;
        int pageCount = 0;
        try {
            pageNo = Integer.parseInt(page.trim());
            pageCount = Math.min(Integer.parseInt(pageSize.trim()), 5000);
        } catch (Exception e) {
            LOGGER.error("get():err-page或者pagesize参数错误");
            return errorRequest();
        }
        //开始进行处理
        serviceID = serviceID.trim();
        // 权限认证
        String[] userInfo = securtiyChecker.getUserInfo(token.trim());
        String userID = userInfo == null ? "" : userInfo[0];
        if (userInfo == null) {
            return noPermit();
        }

        requestParams.put("page", pageNo);
        requestParams.put("pageSize", pageCount);
        requestParams.put("token", token.trim());
        requestParams.put("arg", args.trim());
        requestParams.put("userID", userID);


        //通過ServiceID獲得服務
        try{
            serviceConfig = ObjectPooledFactoy.get("com.yudean.esb.controller.CommonController.get#esbServiceConfig-"+serviceID);
            if (serviceConfig == null) {
                serviceConfig = ServicesCollection.getService(serviceID);
                ObjectPooledFactoy.put("com.yudean.esb.controller.CommonController.get#esbServiceConfig-" + serviceID, serviceConfig);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //健壮性考虑
        if (serviceConfig == null || serviceConfig.getEnableFlag().equals("0")) {
            return errorRequest();
        }
        return universalQueryService.executeService(serviceID, requestParams);
    }
}
